<template>
  <div class="content-import">
    <div>
      <el-link type="primary" @click="importError">导入错误表</el-link>
    </div>
    <p style="text-align: center;padding: 30px 0;font-weight: bold;font-size: 26px" >证件数据导入</p>
    <div>
      <el-steps :active="active" align-center>
        <el-step title="上传基本信息" description="" />
        <el-step title="上传证件照" description="" />
        <el-step title="完成" description="" />
      </el-steps>
    </div>
    <div style="margin-left: 220px;padding: 30px 0;margin-top: 20px">
      <span>请选择证件类型：</span>
      <el-select placeholder="Select" v-model="templateValue" value-key="id" size="large" style="width: 240px;margin-right: 60px">
        <el-option v-for="item in templateList.data" :key="item.id" :label="item.cert.cnName" :value="item"/>
      </el-select>
      <el-button type="primary" @click="downloadTemp">下载导入模板</el-button>
    </div>
    <div style="width: 800px;margin: auto" v-if="!uuIdData">
      <el-upload class="upload-demo" ref="upload" drag accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" :auto-upload="false" action="" multiple :limit="1" :on-change="fielChange" :on-exceed="handleExceed">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          上传基本信息 <em>点击上传</em>
        </div>
      </el-upload>
      <div style="text-align: center;margin-top: 30px">
        <el-button style="width: 300px;" type="primary" @click="bulkImport">下一步</el-button>
      </div>
    </div>
    <div style="width: 800px;margin: auto;padding-top: 100px" v-else>
      <el-upload class="upload-demo" ref="uploads" drag action="" accept=".zip, .rar" :auto-upload="false" multiple :limit="1" :on-change="fielChangeImg" :on-exceed="handleExceedImg">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          上传证件照片 <em>点击上传</em>
        </div>
      </el-upload>
      <span style="color: red">照片文件格式为ZIP,文件命名请使用英文命名</span>
      <div style="text-align: center;margin-top: 30px">
        <el-button style="width: 300px;" type="primary" @click="bulkImportImg">下一步</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import baseURL from '../../http/axios.config.js';
import { ref,reactive } from "vue";
import {
  _carImportData,
  _getCardTypeSet,
  _getTemplateList,
  _importCardImg,
  _importCarImg,
  _importPerson
} from "../../http/api.js";
import {ElLoading, ElMessage, ElMessageBox, genFileId} from "element-plus";
import { UploadFilled } from '@element-plus/icons-vue'
import {useRouter} from "vue-router";

const router = useRouter()
let loginId = '';
let exhibitionId = '';
let t = setInterval(() => {
  loginId = sessionStorage.getItem('loginId');
  exhibitionId = sessionStorage.getItem('projectId');
  if(loginId&&exhibitionId) {
    getTemplateList();
    clearInterval(t);
  }
},200)
const active = ref(0);
const templateValue = ref({}); // 证件类型id
const templateList = reactive({ // 证件类型列表
  data:[]
})
const fieldData = ref({}); // 批量导入文件
const fieldFaceData = ref({}); // 批量导入照片
const upload = ref(); // 上传组件
const uploads = ref(); // 上传组件
const uuIdData = ref('');
//获取模板数据
const getTemplateList = () => {
  const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'});
  _getTemplateList()
      .then(res => {
        console.log(res);
        loading.close();
        if(res.data.ok) {
          let list = res.data.data;
          // templateList.data = res.data.data;
          getCardTypeSet(list)
        }
      })
      .catch(err => {
        console.log(err);
        loading.close();
      })
}
// 获取用户对应证件列表
const getCardTypeSet = (list) => {
  const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'});
  _getCardTypeSet(loginId)
      .then(res => {
        console.log(res);
        loading.close();
        if(res.data.ok) {
          let cardTypeList = res.data.data;
          for (let i = 0; i < list.length; i++) {
            for (let j = 0; j < cardTypeList.length; j++) {
              if(list[i].cert.id === cardTypeList[j].certId) {
                console.log(list[i]);
                templateList.data.push(list[i]);
              }
            }
          }
        }
      })
      .catch(err => {
        console.log(err);
        loading.close();
      })
}
// 下载导入模板
const downloadTemp = () => {
  console.log(templateValue.value);
  if(!templateValue.value.id) return ElMessage({message: '请选择证件类型', type: 'warning' });
  let url = '/api/oly/exit/download/'
  if(templateValue.value.cert.cnName === 'IOC证件') {
    window.open('https://h5.uexpo.com/download/%E5%A2%83%E5%A4%96%E4%BA%BA%E5%91%98%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx')
    // window.open(baseURL.baseURL+url+'1')
  }else if(templateValue.value.cert.cnName === '工作证'){
    window.open('https://h5.uexpo.com/download/%E5%B7%A5%E4%BD%9C%E8%AF%81%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx')
    // window.open(baseURL.baseURL+url+'0')
  }else if(templateValue.value.cert.cnName === '安保证'){
    window.open('https://h5.uexpo.com/download/%E5%AE%89%E4%BF%9D%E4%BA%BA%E5%91%98%E6%A8%A1%E6%9D%BF.xlsx')
    // window.open(baseURL.baseURL+url+'2')
  }else {
    window.open('https://h5.uexpo.com/download/%E8%BD%A6%E8%AF%81%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx')
  }
}
// 文件选择
const fielChange = (files) => {
  console.log(files);
  console.log(upload.value);
  fieldData.value = files.raw;
}
// 超出限制
const handleExceed = (files) => {
  upload.value.clearFiles()
  const file = files[0];
  console.log(file);
  file.uid = genFileId()
  upload.value.handleStart(file);
  fieldData.value = file;
}
//批量导入确定
const bulkImport = () => {
  console.log(templateValue.value);
  if(!templateValue.value.id) return ElMessage.warning('请选择导入的证件类型');
  if(!fieldData.value || !fieldData.value.name) return ElMessage.warning('请选择文件');
  let typeName = templateValue.value.cert.cnName;
  console.log(typeName);
  if(typeName !== 'IOC证件' && typeName !== '工作证' && typeName !== '安保证') {
    carImportData()
  }else {
    importPerson()
  }
}
// 人证导入
const importPerson = () => {
  let type = templateValue.value.cert.cnName === 'IOC证件' ? '1' : '0';
  let state = templateValue.value.cert.enName;
  console.log(templateValue.value.cert.enName);
  const formData = new FormData();
  formData.append('file', fieldData.value);
  formData.append('userId', loginId);
  formData.append('exhibitionId', exhibitionId);
  formData.append('templateId', templateValue.value.id);
  formData.append('type', type);
  formData.append('state', state);
  const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'});
  _importPerson(formData,loginId,exhibitionId,templateValue.value.id,type,state)
      .then(res => {
        console.log(res);
        loading.close();
        if(res.data.ok) {
          let {uuId,count,error} = res.data.data;
          ElMessageBox.alert(`识别到共${count}条数据,导入失败${error?error:0}条`, '提示', {
            confirmButtonText: '确定',
            callback: (action) => {
              if(type === '1') {
                initUpload()
              }else {
                isImportImg(uuId)
              }
            }
          });
        }else {
          ElMessage.warning(res.data.msg)
        }
      })
      .catch(err => {
        console.log(err);
        loading.close();
      })
}
// 车证导入
const carImportData = () => {
  const formData = new FormData();
  formData.append('file', fieldData.value);
  formData.append('userId', loginId);
  formData.append('exhibitionId', exhibitionId);
  formData.append('templateId', templateValue.value.id);
  const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'});
  _carImportData(formData,loginId,exhibitionId,templateValue.value.id)
      .then(res => {
        console.log(res);
        loading.close();
        if(res.data.ok) {
          let {uuId,total,count,error} = res.data.data;
          ElMessageBox.alert(`识别到共${total}条数据,成功${count?count:0}条,失败${error?error:0}条`, '提示', {
            confirmButtonText: '确定',
            callback: (action) => {
              console.log(action);
              isImportImg('car')
            },
          });
        }else {
          ElMessage.warning(res.data.msg)
        }
      })
      .catch(err => {
        console.log(err);
        loading.close();
      })
}
// 选择证件照片
const fielChangeImg = (files) => {
  console.log(files);
  fieldFaceData.value = files.raw;
}
// 证件照片超出
const handleExceedImg = (files) => {
  console.log(files);
  uploads.value.clearFiles()
  const file = files[0];
  console.log(file);
  file.uid = genFileId()
  uploads.value.handleStart(file);
  fieldFaceData.value = file;
}
// 上传证件照片
const bulkImportImg = () => {
  if(!templateValue.value.id) return ElMessage.warning('请选择导入的证件类型');
  if(!fieldFaceData.value || !fieldFaceData.value.name) return ElMessage.warning('请选择文件');
  let typeName = templateValue.value.cert.cnName;
  console.log(typeName);
  if(typeName !== 'IOC证件' && typeName !== '工作证' && typeName !== '安保证') {
    carImgImport(); // 车证照片
  }else {
    personImgImport(); // 人证照片
  }
}

// 人证照片导入
const personImgImport = () => {
  let type = templateValue.value.cert.cnName === 'IOC证件' ? '1' : '0';
  const formData = new FormData();
  formData.append('uploadFile', fieldFaceData.value);
  formData.append('userId', loginId);
  formData.append('exhibitionId', exhibitionId);
  formData.append('templateId', templateValue.value.id);
  formData.append('uuId', uuIdData.value);
  formData.append('type', type);
  const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'});
  _importCardImg(formData,loginId,exhibitionId,templateValue.value.id,uuIdData.value,type)
      .then(res => {
        console.log(res);
        loading.close();
        if(res.data.ok) {
          // let {uuId,count,error} = res.data.data;
          active.value = 3;
          ElMessage({message: res.data.msg, type: 'success' });
          setTimeout(() => {
            initUpload()
          },800)
        }else {
          ElMessage({message: res.data.msg, type: 'error' });
        }
      })
      .catch(err => {
        console.log(err);
        loading.close();
      })
}
// 车证照片导入
const carImgImport = () => {
  const formData = new FormData();
  formData.append('uploadFile', fieldFaceData.value);
  formData.append('userId', loginId);
  formData.append('exhibitionId', exhibitionId);
  formData.append('templateId', templateValue.value.id);
  formData.append('uuId', uuIdData.value);
  const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'});
  _importCarImg(formData,loginId,exhibitionId,templateValue.value.id,uuIdData.value)
      .then(res => {
        console.log(res);
        loading.close();
        if(res.data.ok) {
          // let {uuId,count,error} = res.data.data;
          active.value = 3;
          ElMessage({message: res.data.msg, type: 'success' });
          setTimeout(() => {
            initUpload()
          },800)
        }else {
          ElMessage({message: res.data.msg, type: 'error' });
        }
      })
      .catch(err => {
        console.log(err);
        loading.close();
      })
}

// 导入错误列表
const importError = () => {
  router.push({ path:'/index/importErrorList'})
}

// 是否需要导入照片
const isImportImg = (uuId) => {
  ElMessageBox.confirm('是否继续导入照片数据?', '提示', {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'})
      .then(() => {
        console.log(1);
        uuIdData.value = uuId;
        active.value = 1;
      })
      .catch(() => {
        initUpload();
        console.log(12);

      })
}
// 初始上传状态
const initUpload = () => {
  if(upload.value) {
    upload.value.clearFiles();
  }
  if(uploads.value) {
    uploads.value.clearFiles();
  }
  fieldData.value = {};
  fieldFaceData.value = {};
  active.value = 0;
  uuIdData.value = '';
}

/*// 轮询查询导入状态
const pollState = (uuId,count) => {
  let t = setInterval(() => {
    _importFindState(uuId)
        .then(res => {
          console.log(res);
          if(res.data.ok) {
            let data = res.data.data;
            if(data >= count) {
              ElNotification({title: '提示', message: `共${data}条数据,导入成功`, type: 'success'});
              importLoading.value = false;
              clearInterval(t)
            }
          }
        })
  },1000)
}*/
// const dblclick = () => {
//   uuIdData.value = 1;
// }
</script>



<style scoped lang="scss">
.content-import{
  padding: 30px;
}
</style>